package chaoyue.study.safe;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.TtlRunnable;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 使用阿里提供的 TransmittableThreadLocal 可以解决在线程池复用的情况下，子线程重复读取的问题
 */
public class ThreadLocalTest5 {
    private static ExecutorService executor = Executors.newFixedThreadPool(1);

    private static TransmittableThreadLocal<Integer> threadLocal = new TransmittableThreadLocal<>();

    public static void main(String[] args) {

        for (int i = 0; i < 5; i++) {
            final int count = i;
            threadLocal.set(i);
            System.out.println(Thread.currentThread().getName() + "放入值，值为 : " + i);
            executor.execute(TtlRunnable.get(() -> System.out.println(Thread.currentThread().getName() + "进行取值-" + count + "，值为 : " + threadLocal.get())));
            System.out.println(Thread.currentThread().getName() + "进行取值，值为 : " + threadLocal.get());
            threadLocal.remove();
        }
        executor.close();
    }
}
